import { compose } from "./helpers";

/**
 * redux中间件
 */
export default function applyMiddleware(...middles) {
    return function createStore(createStore) {
        return function reducer(reducers) {
            const store = createStore(reducers);
            let dispatch; // 最终的dispatch不是store中的dispatch
            if (middles.length) { // 有中间件才处理，否则不处理
                const storeApi = {
                    // !注意要传参啊 
                    // 当中间调用这个dispatch就走这个
                    dispatch: (action) => dispatch(action),
                    getState: store.getState
                }
                // 先拨开一层
                const nexts = middles.map(i => i(storeApi));

                // 再拨开一层，到派发action函数这层
                dispatch = compose(...nexts)(store.dispatch); // 传入真正的dispatch
                return {
                    ...store,
                    // 组件调用的dispatch走这个
                    dispatch
                }
            } else {
                return store
            }
        }
    }
}